package org.lpw.wormhole.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lpw.wormhole.WormholeManager;
import org.lpw.wormhole.cache.CacheElement;
import org.lpw.wormhole.cache.LocalCache;
import org.lpw.wormhole.util.Kit;

/**
 * 远程缓存Servlet服务。用于处理基于Servlet的远程缓存同步。
 * 
 * @author lpw
 */
public class RemoteCacheServlet
    extends HttpServlet
{
    private static final long serialVersionUID = -7296907247797238561L;
    private static final String[] TYPES = {"type", "put", "get", "remote"};
    private static final String KEY = "key";
    private static final String ELEMENT = "element";

    protected final Kit kit;
    protected final LocalCache localCache;

    public RemoteCacheServlet()
    {
        super();

        kit = WormholeManager.getInstance().getKit();
        localCache = WormholeManager.getInstance().getCacheFactory().getLocalCache();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        String type = request.getParameter(TYPES[0]);

        if(type==null)
            return;

        if(TYPES[1].equals(type))
        {
            put(request);
        }
        else
        {
            String key = request.getParameter(KEY);

            if(TYPES[2].equals(type))
                get(response, key);
            else if(TYPES[3].equals(type))
                remove(key);
        }
        response.getOutputStream().close();
    }

    /**
     * 执行保存操作。
     * 
     * @param request
     *            请求对象。
     */
    protected void put(HttpServletRequest request)
    {
        String string = request.getParameter(ELEMENT);

        if(string==null)
            return;

        CacheElement element = kit.getConverter().deserializeFromHexString(string);

        if(element!=null)
            localCache.put(element);
    }

    /**
     * 执行获取操作。
     * 
     * @param response
     *            输出对象。
     * @param key
     *            要获取的缓存引用key值。
     * @throws IOException
     *             IO异常。
     */
    protected void get(HttpServletResponse response, String key)
        throws IOException
    {
        CacheElement element = localCache.get(key);
        if(element!=null)
            response.getOutputStream().print(kit.getConverter().serializeToHexString(element));
    }

    /**
     * 执行删除操作。
     * 
     * @param key
     *            要删除的缓存引用key值。
     */
    protected void remove(String key)
    {
        localCache.remove(key);
    }
}
